<template>
  <div class="teams-container">
    <h1>团队管理</h1>
    
    <el-card class="team-card">
      <template #header>
        <div class="card-header">
          <span>我的团队</span>
          <el-button type="primary" @click="showCreateTeamDialog = true">创建团队</el-button>
        </div>
      </template>
      
      <el-table v-if="teams.length > 0" :data="teams" style="width: 100%">
        <el-table-column prop="name" label="团队名称" />
        <el-table-column prop="description" label="团队描述" />
        <el-table-column prop="memberCount" label="成员数量" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="viewTeam(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editTeam(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDeleteTeam(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-empty v-else description="暂无团队数据" />
    </el-card>
    
    <!-- 创建团队对话框 -->
    <el-dialog v-model="showCreateTeamDialog" title="创建团队" width="500px">
      <el-form :model="teamForm" label-width="80px" :rules="rules" ref="teamFormRef">
        <el-form-item label="团队名称" prop="name">
          <el-input v-model="teamForm.name" placeholder="请输入团队名称" />
        </el-form-item>
        <el-form-item label="团队描述" prop="description">
          <el-input v-model="teamForm.description" type="textarea" placeholder="请输入团队描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateTeamDialog = false">取消</el-button>
          <el-button type="primary" @click="createTeam">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑团队对话框 -->
    <el-dialog v-model="showEditTeamDialog" title="编辑团队" width="500px">
      <el-form :model="teamForm" label-width="80px" :rules="rules" ref="teamFormRef">
        <el-form-item label="团队名称" prop="name">
          <el-input v-model="teamForm.name" placeholder="请输入团队名称" />
        </el-form-item>
        <el-form-item label="团队描述" prop="description">
          <el-input v-model="teamForm.description" type="textarea" placeholder="请输入团队描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditTeamDialog = false">取消</el-button>
          <el-button type="primary" @click="updateTeam">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 团队详情对话框 -->
    <el-dialog v-model="showTeamDetailDialog" :title="currentTeam.name + ' - 团队详情'" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="团队名称">{{ currentTeam.name }}</el-descriptions-item>
        <el-descriptions-item label="团队描述">{{ currentTeam.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentTeam.createdAt) }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="team-members">
        <div class="section-header">
          <h3>团队成员</h3>
          <el-button size="small" type="primary" @click="showAddMemberDialog = true">添加成员</el-button>
        </div>
        
        <el-table :data="teamMembers" style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="role" label="角色" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="danger" @click="removeMember(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    
    <!-- 添加成员对话框 -->
    <el-dialog v-model="showAddMemberDialog" title="添加团队成员" width="500px">
      <el-form :model="memberForm" label-width="80px">
        <el-form-item label="用户">
          <el-select v-model="memberForm.userId" placeholder="请选择用户">
            <el-option
              v-for="user in availableUsers"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="memberForm.role" placeholder="请选择角色">
            <el-option label="成员" value="member" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddMemberDialog = false">取消</el-button>
          <el-button type="primary" @click="addMember">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '../utils/format'

// 团队列表
const teams = ref([
  // 这里将来会从API获取数据
  { id: 1, name: '产品开发团队', description: '负责产品规划和开发', memberCount: 5, createdAt: new Date() },
  { id: 2, name: '市场营销团队', description: '负责市场推广和品牌建设', memberCount: 3, createdAt: new Date() }
])

// 表单相关
const teamFormRef = ref()
const teamForm = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入团队名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 对话框控制
const showCreateTeamDialog = ref(false)
const showEditTeamDialog = ref(false)
const showTeamDetailDialog = ref(false)
const showAddMemberDialog = ref(false)

// 当前选中的团队
const currentTeam = ref({
  id: null,
  name: '',
  description: '',
  createdAt: null
})

// 团队成员
const teamMembers = ref([
  { id: 1, username: '张三', email: 'zhangsan@example.com', role: '管理员' },
  { id: 2, username: '李四', email: 'lisi@example.com', role: '成员' }
])

// 可添加的用户
const availableUsers = ref([
  { id: 3, username: '王五', email: 'wangwu@example.com' },
  { id: 4, username: '赵六', email: 'zhaoliu@example.com' }
])

// 添加成员表单
const memberForm = reactive({
  userId: null,
  role: 'member'
})

// 初始化
onMounted(() => {
  // 这里将来会调用API获取团队列表
  // fetchTeams()
})

// 查看团队详情
const viewTeam = (team) => {
  currentTeam.value = { ...team }
  showTeamDetailDialog.value = true
  // 这里将来会调用API获取团队成员
  // fetchTeamMembers(team.id)
}

// 编辑团队
const editTeam = (team) => {
  teamForm.id = team.id
  teamForm.name = team.name
  teamForm.description = team.description
  showEditTeamDialog.value = true
}

// 确认删除团队
const confirmDeleteTeam = (team) => {
  ElMessageBox.confirm(
    `确定要删除团队 "${team.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里将来会调用API删除团队
    // deleteTeam(team.id)
    teams.value = teams.value.filter(t => t.id !== team.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

// 创建团队
const createTeam = () => {
  teamFormRef.value.validate((valid) => {
    if (valid) {
      // 这里将来会调用API创建团队
      // createTeamAPI(teamForm)
      const newTeam = {
        id: Date.now(),
        name: teamForm.name,
        description: teamForm.description,
        memberCount: 1,
        createdAt: new Date()
      }
      teams.value.push(newTeam)
      showCreateTeamDialog.value = false
      ElMessage.success('创建成功')
      resetForm()
    }
  })
}

// 更新团队
const updateTeam = () => {
  teamFormRef.value.validate((valid) => {
    if (valid) {
      // 这里将来会调用API更新团队
      // updateTeamAPI(teamForm)
      const index = teams.value.findIndex(t => t.id === teamForm.id)
      if (index !== -1) {
        teams.value[index] = {
          ...teams.value[index],
          name: teamForm.name,
          description: teamForm.description
        }
      }
      showEditTeamDialog.value = false
      ElMessage.success('更新成功')
      resetForm()
    }
  })
}

// 添加成员
const addMember = () => {
  if (!memberForm.userId || !memberForm.role) {
    ElMessage.warning('请选择用户和角色')
    return
  }
  
  // 这里将来会调用API添加成员
  // addTeamMember(currentTeam.value.id, memberForm)
  
  const user = availableUsers.value.find(u => u.id === memberForm.userId)
  if (user) {
    teamMembers.value.push({
      id: user.id,
      username: user.username,
      email: user.email,
      role: memberForm.role === 'admin' ? '管理员' : '成员'
    })
    
    // 从可用用户中移除
    availableUsers.value = availableUsers.value.filter(u => u.id !== user.id)
    
    // 更新团队成员数量
    const index = teams.value.findIndex(t => t.id === currentTeam.value.id)
    if (index !== -1) {
      teams.value[index].memberCount++
    }
    
    showAddMemberDialog.value = false
    ElMessage.success('添加成功')
    memberForm.userId = null
    memberForm.role = 'member'
  }
}

// 移除成员
const removeMember = (member) => {
  ElMessageBox.confirm(
    `确定要移除成员 "${member.username}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里将来会调用API移除成员
    // removeTeamMember(currentTeam.value.id, member.id)
    
    teamMembers.value = teamMembers.value.filter(m => m.id !== member.id)
    
    // 将用户添加回可用用户列表
    availableUsers.value.push({
      id: member.id,
      username: member.username,
      email: member.email
    })
    
    // 更新团队成员数量
    const index = teams.value.findIndex(t => t.id === currentTeam.value.id)
    if (index !== -1) {
      teams.value[index].memberCount--
    }
    
    ElMessage.success('移除成功')
  }).catch(() => {
    // 取消移除
  })
}

// 重置表单
const resetForm = () => {
  teamForm.id = null
  teamForm.name = ''
  teamForm.description = ''
}
</script>

<style scoped>
.teams-container {
  padding: 20px;
}

.team-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.team-members {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
</style>